<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
          <el-form-item label="区域名称" prop="maName">
            <el-input v-model="queryParams.maName" clearable placeholder="请输入区域名称" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="小区名称" prop="communityName">
            <el-input v-model="queryParams.communityName" clearable placeholder="请输入小区名称" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['wvp:monitorArea:add']" icon="Plus" plain type="primary" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['wvp:monitorArea:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['wvp:monitorArea:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['wvp:monitorArea:export']" icon="Download" plain type="warning" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="monitorAreaList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column v-if="true" align="center" label="区域编号" prop="maId" />
        <el-table-column align="center" label="区域名称" prop="maName" />
        <el-table-column align="center" label="小区编号" prop="communityId" />
        <el-table-column align="center" label="小区名称" prop="communityName" />
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['wvp:monitorArea:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['wvp:monitorArea:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="绑定" placement="top">
              <el-button v-hasPermi="['wvp:monitorArea:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改监控区域对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="500px">
      <el-form ref="monitorAreaFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域名称" prop="maName">
          <el-input v-model="form.maName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="小区名称" prop="communityId">
          <el-select v-model="form.communityId" filterable placeholder="请选择小区" style="width: 240px">
            <el-option v-for="item in communityList" :key="item.communityId" :label="item.name" :value="item.communityId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="MonitorArea" setup>
import {
  addMonitorArea,
  delMonitorArea,
  getMonitorArea,
  listMonitorArea,
  updateMonitorArea
} from "@/api/wvp/monitorArea";
import { MonitorAreaForm, MonitorAreaQuery, MonitorAreaVO } from "@/api/wvp/monitorArea/types";
import { listCommunity } from "@/api/system/community";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const monitorAreaList = ref<MonitorAreaVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const monitorAreaFormRef = ref<ElFormInstance>();
const communityList = ref<Array<any>>([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: MonitorAreaForm = {
  maId: undefined,
  maName: undefined,
  communityId: undefined,
  communityName: undefined,
  remark: undefined
};
const data = reactive<PageData<MonitorAreaForm, MonitorAreaQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    maName: undefined,
    communityId: undefined,
    communityName: undefined,
    params: {}
  },
  rules: {
    maId: [
      { required: true, message: "区域编号不能为空", trigger: "blur" }
    ],
    maName: [
      { required: true, message: "区域名称不能为空", trigger: "blur" }
    ],
    communityId: [
      { required: true, message: "小区编号不能为空", trigger: "blur" }
    ],
    communityName: [
      { required: true, message: "小区名称不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询监控区域列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMonitorArea(queryParams.value);
  monitorAreaList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  monitorAreaFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MonitorAreaVO[]) => {
  ids.value = selection.map(item => item.maId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加监控区域";
  const res2 = await listCommunity();
  communityList.value = res2.rows;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MonitorAreaVO) => {
  reset();
  const _maId = row?.maId || ids.value[0];
  const res = await getMonitorArea(_maId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改监控区域";
  const res2 = await listCommunity();
  communityList.value = res2.rows;
};

/** 提交按钮 */
const submitForm = () => {
  monitorAreaFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.maId) {
        await updateMonitorArea(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addMonitorArea(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MonitorAreaVO) => {
  const _maIds = row?.maId || ids.value;
  await proxy?.$modal.confirm("是否确认删除监控区域编号为\"" + _maIds + "\"的数据项？").finally(() => loading.value = false);
  await delMonitorArea(_maIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("wvp/monitorArea/export", {
    ...queryParams.value
  }, `monitorArea_${new Date().getTime()}.xlsx`);
};
watch(() => form.value.communityId, (val) => {
  const community = communityList.value.find(item => item.communityId === val);
  if (community) {
    form.value.communityName = community.name;
  }
}, { immediate: true });
onMounted(() => {
  getList();
});
</script>
